import { baseRequestClient, requestClient } from '#/api/request';
export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    password?: string;
    username?: string;
    tenantCode?: string;
    loginType?: string;
    code?: string;
    clientId?: string;
    clientSecret?: string;

    goHome?: boolean;
    mode?: 'modal' | 'message' | 'none';
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    accessToken: string;
  }

  export interface RefreshTokenResult {
    data: string;
    status: number;
  }
}

/**
 * 登录
 */
export async function loginApi(data: AuthApi.LoginParams) {
  const { goHome = true, mode, ...loginParams } = data;

  const baseUrl = '/iam/oauth2/token';

  // 过滤掉 undefined 和 null 值
  const filteredParams = Object.fromEntries(
    Object.entries(loginParams).filter(
      ([_, value]) => value !== undefined && value !== null,
    ),
  );

  // 使用 URLSearchParams
  const searchParams = new URLSearchParams(filteredParams);
  const url = `${baseUrl}?${searchParams.toString()}`;
  return requestClient.post<AuthApi.LoginResult>(url, data);
}

/**
 * 刷新accessToken
 */
export async function refreshTokenApi() {
  return baseRequestClient.post<AuthApi.RefreshTokenResult>('/iam/oauth2/refresh', {
    withCredentials: true,
  });
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return baseRequestClient.post('/iam/oauth2/logout', {
    withCredentials: true,
  });
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/iam/system/menu/permissions');
}

/**
 * 获取验证码
 */
export async function getCaptchaApi() {
  return requestClient.get('/iam/captcha');
}
